package com.ysy.tz.mfg.equipment.scale.modbus;

import com.serotonin.modbus4j.serial.SerialPortWrapper;
import com.ysy.tz.mfg.equipment.CommEquipment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

public class ModbusSerialPortWrapper implements SerialPortWrapper {
    private static final Logger LOG = LoggerFactory.getLogger(ModbusSerialPortWrapper.class);

    private CommEquipment commEquipment;

    public ModbusSerialPortWrapper(CommEquipment commEquipment) {
        this.commEquipment = commEquipment;
    }

    @Override
    public void close() throws Exception {
        commEquipment.close();
        //listeners.forEach(PortConnectionListener::closed);
        LOG.debug("Serial port {} closed", commEquipment.getName());
    }

    @Override
    public void open() {
        try {
            commEquipment.connectNoListener();
        } catch (Exception ex) {
            LOG.error("Error opening port : {} for {} ", commEquipment.getPortName(), ex);
        }
    }

    @Override
    public InputStream getInputStream() {
        try {
            return commEquipment.getSerialPort().getInputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public OutputStream getOutputStream() {
        try {
            return commEquipment.getSerialPort().getOutputStream();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int getBaudRate() {
        return commEquipment.getBaudrate();
    }

    @Override
    public int getDataBits() {
        return commEquipment.getDataBits();
    }

    @Override
    public int getStopBits() {
        return commEquipment.getStopBits();
    }

    @Override
    public int getParity() {
        return commEquipment.getParity();
    }

}
